<script lang="ts" setup>
import { Popup, showSuccessToast } from "vant";
import { ref, onMounted } from "vue";
import { Image as VanImage, showLoadingToast, closeToast, List, Loading } from "vant";
import { HomeAxios } from "@/api/home.ts";
import { useI18n } from "vue-i18n";
import sortBy from "lodash";
import { UserStore } from "@/store";
import { RouterEnums } from "@/types";
import { useRouter } from "vue-router";
import { groupLogolist } from "@/utils";
import { judgeLang } from "@/utils";
const userStore = UserStore();
const router = useRouter();
const overlayShow = ref(false);
const { t, locale } = useI18n();
const props = defineProps<{
  listIndex: number;
}>();
//选择的id
const indexNum = ref(0);
//选择栏下标
const tabsListIndex = ref(0);
const opneRightPopup = async () => {
  overlayShow.value = true;
  // let tabId = tabs[3].id;
  // listIndex.value = tabId;
  // window.addEventListener('resize', handleResize);
  //nextTick(() => {
  //获取分组的
  await getGroupClusters();
  const time = setTimeout(() => {
    indexNum.value = props.listIndex;
    const element = document.getElementById(String(props.listIndex));
    if (tabs.value.length > 0) {
      tabsListIndex.value = tabs.value.findIndex(item => item.id === props.listIndex);
    }
    getGameList();
    if (element) {
      //锚点定位
      //block: 'nearest' 确保元素在垂直方向上滚动到视图中最接近的可见区域。
      //inline: 'center' 确保元素在水平方向上滚动到视图中心。
      //behavior:它定义元素出现在可视区内过程的动画，有 auto 和 smootha 两种选择。
      element.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
    }
    clearTimeout(time);
  }, 400);
  //})
};
//点击选择的
const selectGroupType = (item, index) => {
  indexNum.value = item.id;
  const element = document.getElementById(String(indexNum.value));
  if (element) {
    element.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
  }
  tabsListIndex.value = index;
  const tabsData = tabs.value[tabsListIndex.value];
  if (tabsData.Listdata.list.length === 0) {
    getGameList();
  }
};

/*****************************旧的************************************** */
const tabs: any = ref([
  {
    Listdata: {
      pageNo: 1,
      pageSize: 10,
      list: [],
      lonadType: false,
      total: 0,
      intiType: false,
    },
  },
]);
const balance = ref(0);
onMounted(() => {
  //获取用户余额
  balance.value = userStore.balance;

  //监听页面窗口的变化
  //  window.addEventListener('resize', handleResize);
});
//获取分组的
const getGroupClusters = async () => {
  await HomeAxios.getGroupClusters().then((res: any) => {
    // res.list.sort((a, b) => a.id - b.id);
    const index = res.list.findIndex(item => item.groupType === 2);
    if (index !== -1) {
      const [target] = res.list.splice(index, 1);
      res.list.unshift(target); // 把收藏加到数组的开头
    }
    res.list.map((item: any) => {
      item.customLogo = groupLogolist(item.groupName, item.groupType);
      item.Listdata = {
        pageNo: 1,
        pageSize: 12,
        list: [],
        lonadType: false,
        total: 0,
        intiType: false,
      };
    });
    tabs.value = res.list.filter(item => item.state === 0);
  });
};
//游戏列表
const getGameList = () => {
  const tabsData = tabs.value[tabsListIndex.value];
  if (!tabsData.id) {
    return false;
  }
  if (!tabsData.intiType || tabsData.Listdata.list.length < tabsData.Listdata.total) {
    if (tabsData.lonadType) {
      return false;
    }
    tabsData.lonadType = true;
    HomeAxios.gameList({
      groupId: tabsData.id,
      pageNo: tabsData.Listdata.pageNo,
      pageSize: tabsData.Listdata.pageSize,
    })
      .then(res => {
        tabsData.lonadType = false;
        if (res) {
          const data = res.list.map((item: object) => ({ ...item, collectShow: false }));
          const setList = getlist(data);
          tabsData.Listdata.list = tabsData.Listdata.list.concat(setList);
          tabsData.Listdata.total = res.total;
          if (tabsData.Listdata.list.length < tabsData.Listdata.total) {
            tabsData.Listdata.pageNo = tabsData.Listdata.pageNo + 1;
          }
          tabsData.Listdata.intiType = true;
        }
      })
      .catch(() => {
        tabsData.lonadType = false;
      });
  }
};
/*********分组排序组装******************* */
// const arrlist = ref([] as any);
const getlist = list => {
  //list = list.sort((pre, cur) => pre.gameId - cur.gameId);
  // 判断是否有缓存
  //JSON.parse(localStorage.getItem("collectIds") as string);
  // const hasData =
  //   localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid) !== null &&
  //   localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid) !== ""
  //     ? JSON.parse(
  //         localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid) as string,
  //       )
  //     : undefined;
  // if (hasData) {
  // 判断两个数组中的对象id是否相同，如果相同则添加状态字段
  const hasData = JSON.parse(
    localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid) as string,
  );
  //const collectList = ref([]);
  for (const obj1 of list) {
    if (obj1.isCollect === "1") {
      obj1.collectShow = true;
      if (hasData == null) {
        localStorage.setItem(
          "collectIds" + userStore.userLoginInfo.account.uid,
          JSON.stringify([obj1]),
        );
      }
    }

    // for (const obj2 of hasData) {
    //   if (obj1.gameId === obj2.gameId ) {
    //     obj1.collectShow = true;
    //   }
    // }
  }
  //}
  return list;
};
//关闭页面
const closurePopup = () => {
  emits("closurePopup");
  overlayShow.value = false;
};
const emits = defineEmits(["openGameUrl", "closurePopup"]);

//点击打开游戏链接
const getGemoUrl = sortBy.throttle(data => {
  if (userStore.isLogin) {
    showLoadingToast({
      message: "loading...",
      forbidClick: true,
    });
    const item = {
      providerId: data.providerId,
      gameId: data.gameId,
      Lang: judgeLang(locale.value),
    };
    //获取游戏链接1
    HomeAxios.getGameUrl(item).then(res => {
      if (res.url) {
        // getGameUrlData = res
        //获取根据运营商id游戏专属tokne
        HomeAxios.getGameToken({
          providerId: data.providerId,
          op: 1,
        }).then(msg => {
          //根据游戏商运行的ID和token充值2
          HomeAxios.gameRecharge({
            providerId: data.providerId,
            money: "",
            token: msg.token,
          }).then(() => {
            closeToast();
            emits("openGameUrl", res.url);
          });
        });
        closeToast();
      }
    });
  } else {
    router.push(RouterEnums.LOGIN);
  }
}, 1500);
// 点击收藏
const clickCollect = sortBy.throttle(item => {
  if (userStore.isLogin) {
    item.collectShow = !item.collectShow;
    const hasData = JSON.parse(
      localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid) as string,
    );
    if (item.collectShow) {
      // 存收藏
      if (hasData) {
        const lastData = hasData.concat([item]);
        localStorage.setItem(
          "collectIds" + userStore.userLoginInfo.account.uid,
          JSON.stringify(lastData),
        );
      } else {
        localStorage.setItem(
          "collectIds" + userStore.userLoginInfo.account.uid,
          JSON.stringify([item]),
        );
      }
      HomeAxios.clickCollect({ collectType: "1", gameId: item.gameId }).then(() => {
        showSuccessToast(t("home.favoritos"));
      });
    } else {
      // 删除收藏类型 1-收藏 2-取消收藏
      const deletedata = hasData.filter(el => el.gameId !== item.gameId);
      localStorage.setItem(
        "collectIds" + userStore.userLoginInfo.account.uid,
        JSON.stringify(deletedata),
      );
      HomeAxios.clickCollect({ collectType: "2", gameId: item.gameId }).then(() => {
        showSuccessToast(t("home.cancelamento"));
      });
    }
  } else {
    router.push(RouterEnums.LOGIN);
    return false;
  }
}, 1000);
defineExpose({ opneRightPopup });
</script>
<template>
  <div>
    <!-- 首页右边弹窗的游戏列表 -->
    <Popup
      v-model:show="overlayShow"
      position="right"
      style="position: absolute"
      :lock-scroll="true"
      :safe-area-inset-top="true"
      :safe-area-inset-bottom="true"
      :style="{ width: '100%', maxWidth: '642px', height: '100%' }"
      z-index="120"
      @click.self="overlayShow = false"
    >
      <div class="content-frame">
        <div class="daohng-frame">
          <div class="daohng-content df ai-center">
            <div class="fanhui df ai-center jc-center" @click="closurePopup">
              <img src="@/image/new_img/home/dajiantou_bai.png" />
            </div>
            <div class="game-name">{{ t("generalTitle.game") }}</div>
          </div>
        </div>
        <!-- <div class="interval-frame"></div> -->
        <div class="gameList-frame">
          <div class="tabs-frame">
            <div class="tabs">
              <div
                v-for="(tab, index) in tabs"
                :key="tab.id"
                class="imgs-frame df jc-center ai-center"
                :class="{ 'select-img': tab.id === indexNum }"
                :id="tab.id"
                :indexNum="indexNum"
                @click="selectGroupType(tab, index)"
              >
                <img v-if="tab.state === 0" :src="tab.customLogo" />
              </div>
            </div>
          </div>
          <div class="interval-frame2"></div>
          <div class="game-List-frame">
            <List
              :loading="tabs[tabsListIndex].Listdata.lonadType"
              finished-text="No more"
              :finished="
                tabs[tabsListIndex].Listdata.intiType &&
                tabs[tabsListIndex].Listdata.list.length === tabs[tabsListIndex].Listdata.total
              "
              @load="getGameList"
              offset="500"
            >
              <div class="df fw-wrap game-list-content-frame">
                <div
                  v-for="(item, index) in tabs[tabsListIndex].Listdata.list"
                  :key="index"
                  class="img-frame"
                  :id="item.gameId"
                >
                  <VanImage
                    class="game-img-style"
                    fit="contain"
                    :src="item.gameLogo"
                    @click="getGemoUrl(item)"
                    :id="item.id"
                  >
                    <template v-slot:loading>
                      <Loading type="spinner" size="40" />
                    </template>
                  </VanImage>
                  <img
                    v-show="item.collectShow"
                    class="collect-img"
                    src="@/image/new_img/home/bofang_caise.png"
                    @click.stop="clickCollect(item)"
                  />
                  <img
                    v-show="!item.collectShow"
                    class="collect-img"
                    src="@/image/new_img/home/shoucang_bai.png"
                    @click.stop="clickCollect(item)"
                  />
                </div>

                <div
                  class="bottom-frame"
                  v-show="
                    !tabs[tabsListIndex].Listdata.intiType ||
                    tabs[tabsListIndex].Listdata.list.length < tabs[tabsListIndex].Listdata.total
                  "
                >
                  <div class="loadMore-frame df jc-center ai-center" @click="getGameList">
                    {{ t("generalTitle.loadMore") }}

                    <img class="loadmore-img" src="@/image/new_img/gamelist/loadmore_bai.png" />
                  </div>
                  <!-- <div
                    class="loadMore-frame df jc-center ai-center"
                    v-show="
                      tabs[tabsListIndex].Listdata.intiType &&
                      tabs[tabsListIndex].Listdata.list.length ===
                        tabs[tabsListIndex].Listdata.total
                    "
                  >
                    {{ t("tip.nomore") }}
                  </div> -->
                </div>
                <!-- <div class="bottom-frame"></div> -->
              </div>
            </List>
          </div>
        </div>
      </div>
    </Popup>
  </div>
</template>
<style lang="less" scoped>
.content-frame {
  width: 100%;
  height: 100%;
  background: #1b0a24;
  position: relative;
  left: 0;
  top: 0;
  overflow: hidden;

  .daohng-frame {
    // position: absolute;
    // left: 0;
    // top: 0;
    width: 100%;
    height: 105px;
    z-index: 50;

    .daohng-content {
      width: 100%;
      height: 100%;
      position: relative;
      left: 0;
      top: 0;
    }

    .wan-zan-dizi {
      width: 129px;
      height: 36px;
      margin-right: 36px;
    }

    .fanhui {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 30px;
      z-index: 2;
      width: 76px;
      height: 76px;
      border-radius: 50%;
      background-color: #ffffff1a;
      img {
        width: 30px;
        height: 30px;
        transform: rotate(180deg);
      }
    }
  }

  .game-name {
    color: #ffffff;
    font-size: 32px;
    font-weight: 700;
    width: auto;
    margin: auto;
  }
}

.interval-frame {
  width: 100%;
  height: 82px;
}

.content-frame::-webkit-scrollbar {
  display: none;
}

.game-list-content-frame::-webkit-scrollbar {
  display: none;
}

.gameList-frame {
  width: calc(100% - 60px);
  margin: auto;
  height: calc(100vh - 266px);
  margin-left: 30px;
  position: relative;
  left: 0px;
  right: 0px;
  margin-top: 20px;
}

.tabs-frame {
  width: 100%;
  margin: auto;
  height: auto;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 50;

  .tabs {
    width: 100%;
    display: flex;
    overflow-x: auto;
    position: absolute;
  }

  .tabs::-webkit-scrollbar {
    display: none;
  }

  .imgs-frame {
    width: auto;
    height: 68px;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 17px;
    margin-right: 13px;
    padding-left: 22px;
    padding-right: 22px;
    img {
      width: 132px;
      height: 68px;
    }
  }

  .select-img {
    background-image: linear-gradient(
      64deg,
      rgba(254, 121, 25, 0.5) 0%,
      rgba(171, 63, 231, 0.5) 100%
    );
    border: 1px solid rgba(171, 63, 231, 1);
  }
}

.interval-frame2 {
  width: 100%;
  height: 80px;
}

.bottom-frame {
  width: 100%;
  height: 151px;
}

.img-frame {
  width: 218px;
  height: 290px;
  margin-bottom: 17px;
  border-radius: 28px;
  position: relative;
  top: 0;
  left: 0;
  overflow: hidden;
  margin-right: 15px;

  .collect-img {
    width: 48px;
    height: 48px;
    background: rgba(0, 0, 0, 0.65);
    padding: 7px;
    position: absolute;
    right: 6px;
    top: 6px;
    border-radius: 50%;
  }

  .game-img-style {
    width: 218px;
    height: 290px;
    border-radius: 28px;
  }
}

.img-frame:nth-child(3n + 0) {
  margin-right: 0px;
}

.game-list-content-frame {
  width: 100%;
  height: 100%;
  margin-top: 40px;
}

.loadMore-frame {
  font-size: 25px;
  background: rgba(255, 255, 255, 0.04);
  color: rgba(255, 255, 255, 0.65);
  width: 317px;
  height: 63.3px;
  border-radius: 63.3px;
  margin: auto;
  margin-top: 32px;
  .loadmore-img {
    width: 24px;
    height: 24px;
    margin-left: 6px;
  }
}
.arrow-frame {
  margin-left: 8px;
  transform: rotate(90deg);
  font-size: 40px;
}

.game-List-frame {
  width: 100%;
  height: auto;
  height: calc(100vh - 266px);
  overflow-y: auto;
  &::-webkit-scrollbar {
    display: none;
    overflow: -moz-scrollbars-none; /* Firefox */
    -ms-overflow-style: none; /* IE 和 Edge */
  }
}
:deep(.van-list) {
  &::-webkit-scrollbar {
    display: none;
    overflow: -moz-scrollbars-none; /* Firefox */
    -ms-overflow-style: none; /* IE 和 Edge */
  }
}
.game-list-frame::-webkit-scrollbar {
  display: none;
  overflow: -moz-scrollbars-none; /* Firefox */
  -ms-overflow-style: none; /* IE 和 Edge */
}
</style>
